# app/routes/movie_routes.py
from flask import Blueprint, render_template, request
from flask_login import login_required, current_user
from app.models.movie import Movie

movie_bp = Blueprint('movie', __name__)


@movie_bp.route('/movie_search', methods=['GET', 'POST'])
@login_required
def movie_search():
    movies = []
    error = None
    release_year = request.form.get('release_year', '').strip()
    title_keyword = request.form.get('title_keyword', '').strip()

    query = Movie.select()

    # 处理年份输入
    if release_year:
        try:
            year = int(release_year)  # 转换为整数
            query = query.where(Movie.year == year)
        except ValueError:
            error = "请输入有效的年份（如：2023）"
            return render_template('signin-ok.html',
                                   username=current_user.username,
                                   error=error,
                                   release_year=release_year)

    # 处理标题关键词
    if title_keyword:
        query = query.where(Movie.title.contains(title_keyword))  # Peewee会自动添加%通配符

    movies = list(query.order_by(Movie.title))

    # 如果没有结果且没有错误，显示“未找到”
    if not movies and not error:
        error = "未找到符合条件的电影"

    return render_template('signin-ok.html',
                           username=current_user.username,
                           movies=movies,
                           release_year=release_year,
                           error=error)

